package com.lwj.liwanjia.view.activity.work.shang_jia;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.FaBuHomeAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.AddressBean;
import com.lwj.liwanjia.bean.WorkBean01;
import com.lwj.liwanjia.bean.WorkBean02;
import com.lwj.liwanjia.bean.WorkBean03;
import com.lwj.liwanjia.config.URLConstant;
import com.lwj.liwanjia.utils.SpUtils;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.address.AddressActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 001 on 2017/9/11.
 */

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 0:
                    Toast.makeText(RegisterActivity.this, "八大分类接口有问题", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(RegisterActivity.this, "八大分类数据获取失败", Toast.LENGTH_SHORT).show();
                    break;
                case 2:

                    if (typeList != null && typeList.size() >= 0) {

                        typeAdapter = new FaBuHomeAdapter(RegisterActivity.this, typeList);
                        popupListView.setAdapter(typeAdapter);

                    }

                    break;
                case 3:
                    Toast.makeText(RegisterActivity.this, "头像上传接口有问题", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(RegisterActivity.this, "头像上传数据失败", Toast.LENGTH_SHORT).show();
                    break;
                case 5:

                    if (!TextUtils.isEmpty(photoUrlToken)) {

                        switch (photoType) {

                            case 0:

                                Glide.with(RegisterActivity.this).load(photoUrlToken).into(iv_photo);
                                break;
                            case 1:

                                Glide.with(RegisterActivity.this).load(photoUrlToken).into(iv_dianZhan);
                                break;
                            case 2:

                                Glide.with(RegisterActivity.this).load(photoUrlToken).into(iv_zhiZhao);
                                break;
                        }


                    }

                    break;
                case 6:
                    Toast.makeText(RegisterActivity.this, "注册接口有误", Toast.LENGTH_SHORT).show();
                    break;
                case 7:
                    Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                    break;
                case 8:

                    startActivity(new Intent(RegisterActivity.this, WoShiShangJiaActivity.class));
                    Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                    finish();

                    break;
            }
        }
    };

    private TextView tv_back;
    private TextView tv_title;
    private Button bt_shenQing;
    private RelativeLayout rl_fenLei;//分类 UI 容器
    private ListView popupListView;//分类 弹窗 容器
    private FaBuHomeAdapter typeAdapter;//分类 适配器
    private List<WorkBean01.DataBean> typeList;//分类 数据集合
    private PopupWindow typePopup;//分类 窗口
    private TextView tv_type;//分类 字段

    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
    private OkHttpClient mOkHttpClient;
    private CircleImageView iv_photo;//头像
    private String photoUrl01;//店铺头像URL
    private String photoUrl02;//店招URL
    private String photoUrl03;//营业执照URL
    private String photoUrlToken;//带Token的店铺头像URL
    private int photoType = -1;//上传照片的三种类型 0:头像 1:店招 2:营业执照
    private ImageView iv_dianZhan;//店铺招牌
    private ImageView iv_zhiZhao;//营业执照
    private EditText et_name;//店铺名称
    private EditText et_name02;//申请人名字
    private EditText et_telephone;//电话
    private EditText et_jieShao;//介绍
    private String typeId;//商铺类型对应的ID
    private LinearLayout llTvAddress;
    private TextView tvAddress;
    private String condigneeId;

    @Override
    protected void initView() {

        tv_back = (TextView) findViewById(R.id.tv_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        bt_shenQing = (Button) findViewById(R.id.bt_shenQing);
        rl_fenLei = (RelativeLayout) findViewById(R.id.rl_fenLei);
        iv_dianZhan = (ImageView) findViewById(R.id.iv_dianZhan);
        iv_zhiZhao = (ImageView) findViewById(R.id.iv_zhiZhao);

        iv_photo = (CircleImageView) findViewById(R.id.iv_photo);
        et_name = (EditText) findViewById(R.id.et_name);
        tv_type = (TextView) findViewById(R.id.tv_type);
        et_name02 = (EditText) findViewById(R.id.et_name02);
        et_telephone = (EditText) findViewById(R.id.et_telephone);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        et_jieShao = (EditText) findViewById(R.id.et_jieShao);

        tv_back.setVisibility(View.VISIBLE);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("注册");

        llTvAddress = (LinearLayout) findViewById(R.id.ll_tv_address);

        tv_back.setOnClickListener(this);
        bt_shenQing.setOnClickListener(this);
        rl_fenLei.setOnClickListener(this);
        iv_photo.setOnClickListener(this);
        iv_dianZhan.setOnClickListener(this);
        iv_zhiZhao.setOnClickListener(this);
        llTvAddress.setOnClickListener(this);

    }

    @Override
    protected void initData() {

        //初始化分类的PopupWindow
        initTypePw();

        //分类的条目点击事件
        popupListViewOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register_work;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.tv_left:
                finish();
                break;
            //分类
            case R.id.rl_fenLei:

                //八大分类 连网获取数据
                initOkHttpType();
                typePopup.showAsDropDown(tv_type);

                break;
            //头像
            case R.id.iv_photo:

                photoType = 0;
                toPicture();

                break;
            //店铺招牌
            case R.id.iv_dianZhan:

                photoType = 1;
                toPicture();

                break;
            //营业执照
            case R.id.iv_zhiZhao:

                photoType = 2;
                toPicture();

                break;
            case R.id.ll_tv_address://选择地址
                Intent intent = new Intent(this, AddressActivity.class);
                intent.putExtra("type", "商家注册");
                startActivityForResult(intent, 1);
                break;
            //申请
            case R.id.bt_shenQing:

                String name = et_name.getText().toString().trim();
                String type = tv_type.getText().toString().trim();
                String name02 = et_name02.getText().toString().trim();
                String telephone = et_telephone.getText().toString().trim();
//                String address = tvAddress.getText().toString().trim();
                String jieShao = et_jieShao.getText().toString().trim();

                if (!TextUtils.isEmpty(name)
                        && !TextUtils.isEmpty(type)
                        && !TextUtils.isEmpty(name02)
                        && !TextUtils.isEmpty(telephone)
                        && !TextUtils.isEmpty(condigneeId)
                        && !TextUtils.isEmpty(jieShao)
                        && !TextUtils.isEmpty(photoUrl01)
                        && !TextUtils.isEmpty(photoUrl02)
                        && !TextUtils.isEmpty(photoUrl03)
                        && !TextUtils.isEmpty(typeId)) {

                    //请求网络,申请注册
                    initRegister(name, type, name02, telephone, condigneeId, jieShao);

                } else {
                    Toast.makeText(RegisterActivity.this, "必须全部填写", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                //启动相册后的操作
                case 1002:

                    if (data == null) {
                        return;
                    } else {
                        if (data.getData() != null) {
                            cropPicture(data.getData());
                        }
                    }

                    break;
                //裁剪后的操作
                case 1003:
                    //有可能点击不要这张图片
                    try {
                        if (data != null) {

                            Bundle bundle = data.getExtras();
                            if (bundle != null) {
                                Bitmap bitmap = bundle.getParcelable("data");
                                //将要保存图片的路径
                                File photoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "yi_yun.jpg");
                                //尺寸压缩照片
                                compressBitmapToFile(bitmap, photoFile);
                                //请求网络,上传照片
                                initPhoto(photoFile);
                            }
                        }

                    } catch (Exception e) {
                    }
                    break;
                //选择地址
                case 1:
                    AddressBean.DataBean addressBean = (AddressBean.DataBean) data.getSerializableExtra("address");
                    tvAddress.setText(addressBean.getConsigneeAddress());
                    condigneeId = addressBean.getCondigneeId();
                    break;
            }
        }
    }

    //分类的PopupWindow
    private void initTypePw() {

        View popupView = View.inflate(this, R.layout.popupwindow_fa_bu_home, null);
        typePopup = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        typePopup.setBackgroundDrawable(new ColorDrawable());

        popupListView = (ListView) popupView.findViewById(R.id.listView);
    }

    //八大分类的条目点击事件
    private void popupListViewOnClick() {

        popupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                WorkBean01.DataBean dataBean = typeList.get(position);
                tv_type.setText(dataBean.getScope());
                typeId = String.valueOf(dataBean.getId());
                typePopup.dismiss();
            }
        });
    }

    //启动相册
    public void toPicture() {

        try {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");//全部图片
            startActivityForResult(intent, 1002);
        } catch (Exception e) {
        }

    }

    //裁剪
    public void cropPicture(Uri uri) {

        if (uri == null) {
            return;
        }

        //跳转到裁剪
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");//裁剪所有图片
        //设置裁剪
        intent.putExtra("crop", "true");
        //裁剪宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //裁剪图片的质量
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        //发送数据
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 1003);
    }

    //尺寸压缩照片
    public void compressBitmapToFile(Bitmap bmp, File file) {

        // 尺寸压缩倍数,值越大，图片尺寸越小
        int ratio = 2;

        // 压缩Bitmap到对应尺寸
        Bitmap result = Bitmap.createBitmap(bmp.getWidth() / ratio, bmp.getHeight() / ratio, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, bmp.getWidth() / ratio, bmp.getHeight() / ratio);
        canvas.drawBitmap(bmp, null, rect, null);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        result.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //请求网络,上传照片
    private void initPhoto(File photoFile) {

        String url = URLConstant.BASE_URL + "file/upload";
        mOkHttpClient = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("token",SpfUtils.getSpfUtils(this).getToken())
                .addFormDataPart("file0", photoFile.getName(), RequestBody.create(MEDIA_TYPE_MARKDOWN, photoFile))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String result = null;

                try {
                    result = response.body().string();
                    Log.d("Tag", result);
                    parsePhoto(result);
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(3);
                }


            }
        });
    }

    //解析店铺头像
    private void parsePhoto(String result) {

        Gson gson = new Gson();
        WorkBean02 bean = gson.fromJson(result, WorkBean02.class);

        if (bean != null) {

            switch (bean.getState()) {

                case 0:
                    mHandler.sendEmptyMessage(4);
                    break;
                case 1:

                    //String url = bean.getData().getUrl();

                    photoUrlToken = bean.getData().getUrl();

                    switch (photoType) {

                        case 0:
                            photoUrl01 = bean.getData().getUrl();
                            break;
                        case 1:
                            photoUrl02 = bean.getData().getUrl();
                            break;
                        case 2:
                            photoUrl03 = bean.getData().getUrl();
                            break;
                    }


                    mHandler.sendEmptyMessage(5);

                    break;
            }
        }
    }

    //八大分类 数据 适配器
    private void initOkHttpType() {

        String url = URLConstant.BASE_URL + "shop/getType";
        String token = SpfUtils.getSpfUtils(this).getToken();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("token", token)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.d("Tag", "分类数据获取失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //Log.d("Tag", "分类图数据获取成功");

                String result = null;

                try {
                    result = response.body().string();
                    //Log.d("Tag",result);
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(0);
                }

                parseType(result);
            }
        });
    }

    //解析八大分类
    private void parseType(String result) {

        Gson gson = new Gson();
        WorkBean01 bean = gson.fromJson(result, WorkBean01.class);

        if (bean != null) {

            switch (bean.getState()) {

                case 0:
                    mHandler.sendEmptyMessage(1);
                    break;
                case 1:

                    typeList = new ArrayList<>();

                    for (int i = 0; i < bean.getData().size(); i++) {

                        WorkBean01.DataBean dataBean = bean.getData().get(i);
                        typeList.add(dataBean);
                    }

                    mHandler.sendEmptyMessage(2);

                    break;
            }
        }
    }

    //请求网络,申请注册
    private void initRegister(String name, String type, String name02, String telephone, String address, String jieShao) {

        String url = URLConstant.BASE_URL + "shop/application";
        String token = SpfUtils.getSpfUtils(this).getToken();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("shopname", name)
                .add("shopintroduction", jieShao)
                .add("address", condigneeId)//方便裁剪将传地址改为传地址ID
                .add("scope", typeId)
                .add("shoptele", telephone)
                .add("shopkeeper", name02)
                .add("iswebshop", "0")
                .add("shopimage", photoUrl01)
                .add("shopsign", photoUrl02)
                .add("license", photoUrl03)
                .add("token", token)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = null;
                try {
                    result = response.body().string();
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(6);
                }

                parseRegister(result);
            }
        });
    }

    //解析注册数据
    private void parseRegister(String result) {

        Gson gson = new Gson();
        WorkBean03 bean = gson.fromJson(result, WorkBean03.class);

        if (bean != null) {

            switch (bean.getState()) {

                case 0:
                    mHandler.sendEmptyMessage(7);
                    break;
                case 1:

                    mHandler.sendEmptyMessage(8);

                    break;
            }
        }
    }

}
